﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Kontrolki;
using KPWeb.Class;
using KPWeb.Data;
using KPWeb.Function;
using KPWeb.Reports;
using MSExcel = Microsoft.Office.Interop.Excel;
//using Microsoft.Reporting.WebForms;


namespace KPWeb.Dyzury
{
    public partial class DyzuryWypelnianie : KPPage
    {
        private readonly string[] MonthNames = { "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" };
      
 
        private short RokPlany
        {
            get
            {
                if (ViewState["RokPlany"] == null) ViewState["RokPlany"] = DateTime.Now.Year;
                 return short.Parse(ViewState["RokPlany"].ToString());
            }
            set
            {
                ViewState["RokPlany"] = value;

            }

        }
        private short MiesiacPlany
        {
            get
            {
                if (ViewState["MiesiacPlany"] == null) ViewState["MiesiacPlany"] = DateTime.Now.Month;
                return short.Parse(ViewState["MiesiacPlany"].ToString());
            }
            set
            {
                ViewState["RokPlany"] = value;

            }

        }

        private void initCalendar(CalendarUC  cal, Boolean edytuj, DateTime date)
        {
            cal.AllowHolidaysChecking = true;
            cal.DateStart = date;
            cal.IsDisabled = !edytuj;
           // cal.SingleMonthDate = DateTime.Now.Date; // new DateTime(2013, 12, 1);//

            List<DateTime> l = new List<DateTime>();
            foreach (var item in Kalendarz.GetSwieta(DateTime.Now.Date.Year))
            {
              if(item.month==MiesiacPlany)  l.Add(new DateTime(item.year, item.month, item.day));
            }
            cal.Holidays = l.ToArray();
            cal.ClearSelected();
        }


        private void komunikatError(int kod)//, int iT, int iID)
        {
            fError.Visible = true;
            switch (kod)
            {
                case -1: Error1.Visible = true;
                    break;
                case -2: Error2.Visible = true;
                    break;
                case -3: Error3.Visible = true;
                    break;
                case -4: Error4.Visible = true;
                    break;
                case -5: Error5.Visible = true;
                    break;
                default: fError.Visible = false;
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            fError.Visible = false;
            Error1.Visible = false;
            Error2.Visible = false;
            Error3.Visible = false;
            Error4.Visible = false;
            Error5.Visible = false;


            if (!IsPostBack)
            {

                //this.CalendarUCGJ1.AllowHolidaysChecking = true;
                //this.CalendarUCGJ1.ShowYearCombo = false;
                //this.CalendarUCGJ1.SingleMonthMode = true;
                //this.CalendarUCGJ1.SingleMonthDate = DateTime.Now.Date; // new DateTime(2013, 12, 1);//

                //List<DateTime> l = new List<DateTime>();
                //foreach (var item in Kalendarz.GetSwieta(DateTime.Now.Date.Year))
                //{
                //    l.Add(new DateTime(item.year, item.month, item.day));
                //}
                //this.CalendarUCGJ1.Holidays = l.ToArray();
                //CalendarUCGJ1.ClearSelected();



                initCalendar(CalendarUCGJ,false,new DateTime(2013,8,1));
                initCalendar(CalendarUCGM, true, new DateTime(2013, 8, 1));
                initCalendar(CalendarUCRJ, false, new DateTime(2013, 8, 1));
                initCalendar(CalendarUCRM, true, new DateTime(2013, 8, 1));

             

                //3 usunąć ****
                this.DyzuryID.Text = "62";
              //  this.DyzuryIDRezerwa.Text = "60";
                this.DyzuryKod.Text = "DJ103";
                this.DyzuryOpis.Text ="Dyżury należy koniecznie wprowadzić do 28.08.2013";


               //var qOsoby = from item in DyzuryK.GetListaOsobDyzury(int.Parse(Current.JednostkaID),52)
               //              select new { item.NazwiskoImie, item.OsobaID, item.Tytul, item.DokumentID };

           
             
               IEnumerable<DateTime> qJednostkaDyzury = from item1
                         in DyzuryK.GetDyzuryDlaJednostkiBezOsoby(int.Parse(DyzuryID.Text), int.Parse(Current.OsobaID))
                                                    select item1.Date;
               IEnumerable<DateTime> qOsobaDyzury = from item2
                    in DyzuryK.GetDyzuryDlaOsoby(int.Parse(Current.OsobaID), int.Parse(DyzuryID.Text))
                                                    select item2.Date;
               List<DateTime> l = new List<DateTime>();
               List<DateTime> lOsoba = new List<DateTime>();
              
                foreach (DateTime item in qJednostkaDyzury.Distinct())
                {
                    l.Add(new DateTime(item.Year, item.Month, item.Day));
                }
                foreach (DateTime item in qOsobaDyzury.Distinct())
               {
                   l.Add(new DateTime(item.Year, item.Month, item.Day));
                   lOsoba.Add(new DateTime(item.Year, item.Month, item.Day));
               }
               CalendarUCGJ.Selected = l.ToArray();
         
                foreach (DateTime item in lOsoba)
               {
                   CalendarUCGM.AddUnavailablePeriod(item.Date, item.Date);
               }
              
               CalendarUCGM.Selected = lOsoba.ToArray();


//rezerwa
    this.DyzuryID.Text = "60";
                qJednostkaDyzury = from item1
                                       in DyzuryK.GetDyzuryDlaJednostkiBezOsoby(int.Parse(DyzuryID.Text), int.Parse(Current.OsobaID))
                                                        select item1.Date;
                qOsobaDyzury = from item2
                    in DyzuryK.GetDyzuryDlaOsoby(int.Parse(Current.OsobaID), int.Parse(DyzuryID.Text))
                                                    select item2.Date;
                l.Clear();
                lOsoba.Clear(); 

               foreach (DateTime item in qJednostkaDyzury.Distinct())
               {
                   l.Add(new DateTime(item.Year, item.Month, item.Day));
               }
               foreach (DateTime item in qOsobaDyzury.Distinct())
               {
                   l.Add(new DateTime(item.Year, item.Month, item.Day));
                   lOsoba.Add(new DateTime(item.Year, item.Month, item.Day));
               }
               CalendarUCRJ.Selected = l.ToArray();

               foreach (DateTime item in lOsoba)
               {
                   CalendarUCRM.AddUnavailablePeriod(item.Date, item.Date);
               }

               CalendarUCRM.Selected = l.ToArray();




             
   //////////////////////////
               //int os = int.Parse(Current.OsobaID);

               //IEnumerable<DateTime> qOsobaDyzury = from item2
               //          in DyzuryK.GetDyzuryDlaOsoby(int.Parse(Current.OsobaID), int.Parse(DyzuryID.Text))
               //                                     select item2.Date;
               //l.Clear();
               //foreach (DateTime item in qOsobaDyzury.Distinct())
               //{
               //    l.Add(new DateTime(item.Year, item.Month, item.Day));
               //}
               //CalendarUC1.Selected = l.ToArray();
                /////////////////////////////////
                lYear.Items.Clear();
                foreach (short item in Kalendarz.GetYearGdzieWpisanoSwieta())
                {
                       if (RokPlany >= short.Parse(item.ToString())) this.lYear.Items.Add(item.ToString());
                }

                lYear.SelectedValue = RokPlany.ToString();
                hJednostkaID.Value = Current.JednostkaID;
            
            }
            else
            {
                this.CalendarUCGJ.RenderCalendar();
                this.CalendarUCGM.RenderCalendar();
                this.CalendarUCRJ.RenderCalendar();
                this.CalendarUCRM.RenderCalendar();
            }

        }

        protected void PlanyDyzurow_Click(object sender, System.EventArgs e)
        {

            //int outProc = DyzuryK.InsertPlanyDyzurow(
            //   int.Parse(dTypDyzuru.SelectedValue),
            //   tOpis.Text,
            //   dOd,
            //   new DateTime(RokPlany, iMonth, DateTime.DaysInMonth(RokPlany, iMonth)),
            //   int.Parse(Current.JednostkaID), dd1, dd2,
            //    int.Parse(Current.OsobaID));
            //if (outProc < 0)
            //{
            //    komunikatError(outProc);
            //    return;
            //}


            bool btemp = false;
            if (DyzuryK.DeleteOsobyDyzury (int.Parse(Current.OsobaID), RokPlany,7) != 0)
            {
                btemp = true;
            }
            else
                foreach (DateTime d in this.CalendarUCGJ.Selected)
                {
                    if (DyzuryK.InsertOsobyDyzury(60,int.Parse(Current.OsobaID), d.Date,0) != 0)
                    {
                            btemp = true;
                    }

                }
            if (btemp)
            {
                this.fError.Visible = true;
                Error3.Visible = true;
            }




            this.ListView1.DataBind();
        }

        protected void dyzuryRLBRoboczy_Click(object sender, System.EventArgs e)
        {
            string sTemp = ((KPWeb.Kontrolki.RaportLinkButton)sender).CommandArgument.ToString();
            for (int i = sTemp.Length; i < Stale.countDigitsInBarCode - 2; i++)
            {
                sTemp = "0" + sTemp;
            }
            sTemp = Stale.idWU + sTemp;
            RaportyPDF.RaportWniosekUrlopowyBarCodePDF(int.Parse(sTemp), 0);
        }
 
        protected void btnWypelnijClick(object sender, EventArgs e)
        {
        //    this.fDyzuryWypelnianie.Visible = true;  ####

            this.DyzuryID.Text =((Label)((Button)sender).Parent.FindControl("ID")).Text.ToString();
            this.DyzuryKod.Text = ((Label)((Button)sender).Parent.FindControl("Kod")).Text.ToString();
            this.DyzuryOpis.Text = ((Label)((Button)sender).Parent.FindControl("Opis")).Text.ToString();
            //int outProc = DyzuryK.DeletePlanyDyzurow(
            //               int.Parse(((Button)sender).CommandArgument.ToString()));
            //if (outProc < 0)
            //{
            //    komunikatError(outProc);
            //    return;
            //}

        }
    
     
        protected void lKody_Click(object sender, EventArgs e)
        {
            Server.Transfer("~/Slowniki/TypyDyzurow.aspx");


        }
        protected void CalendarUC_UserControlRefreshedE(object sender, CalendarUC.ActionEvent e)
        {
            //tutaj odswiez u siebie dni dla M (Moje)

            //int iDni = CalendarUC1.Selected.Count();
            //tZaznaczone.Text = iDni.ToString();
            //tRobocze.Text = Kalendarz.GetLiczbaDniRoboczych(CalendarUC1.Selected).ToString();
            if (sender == null) return;
            if (e.ActionType == CalendarUC.ActionType.PageLoad)
            {
                (sender as CalendarUC).ClearUnavailablePeriods();
                DateTime since = new DateTime((sender as CalendarUC).DateStart.Year, (sender as CalendarUC).DateStart.Month, 1);
                DateTime until = new DateTime(since.Year, since.Month, DateTime.DaysInMonth(since.Year, since.Month));

                DateTime zatrOd = DateTime.Parse(Current.DataZatrudnieniaOd);
                DateTime zatrDo = DateTime.Parse(Current.DataZatrudnieniaDo);

                if (zatrOd > since && zatrOd > until || zatrDo < since && zatrDo < until) (sender as CalendarUC).AddUnavailablePeriod(since, until);
                else
                    if (zatrOd > since && zatrOd < until) (sender as CalendarUC).AddUnavailablePeriod(since, zatrOd.AddDays(-1));

                if (zatrDo > since && zatrDo < until) (sender as CalendarUC).AddUnavailablePeriod(zatrDo.AddDays(1), until);
            }
        }
      

        protected int DyzuryWyswietlExcel1(byte typ,  int year, int month1, int month2) //0 bez tytułów, 1 ztytułami
        // 0 OK
        {
            int iTemp = 0;


            MSExcel.Application excelApp = new MSExcel.Application();
            string filePath = Server.MapPath("~/EXCEL/SzDyzury.xls");

            MSExcel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath,
                    0, true, 5, "", "", false, MSExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            MSExcel.Sheets excelSheets = excelWorkbook.Worksheets;

            string currentSheet = "ZestawienieUrlopy";
            MSExcel.Worksheet excelWorksheet = (MSExcel.Worksheet)excelSheets.get_Item(currentSheet);

            MSExcel.Range excelCell;
            MSExcel.Range excelCellTarget;
            MSExcel.Range excelCellSource;
            //f,r ad,2,3
            excelCell = (MSExcel.Range)excelWorksheet.get_Range("I1", "I1");
            excelCell.Value = "Plany dyżurów nr: ROBOCZE";

            excelCell = (MSExcel.Range)excelWorksheet.get_Range("I3", "I3");
            excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
            excelCell.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DodgerBlue);
            excelCell.Offset[1, 1].Value = "";


          //  excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;



            excelCell = (MSExcel.Range)excelWorksheet.get_Range("P3", "P3");
            excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
            excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
            excelCell = (MSExcel.Range)excelWorksheet.get_Range("AA3", "AA3");
            excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlDouble;
            excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlDouble;
            excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalDown].LineStyle = MSExcel.XlLineStyle.xlDouble;

            excelCell = (MSExcel.Range)excelWorksheet.get_Range("C1", "C1");
            vKP_JednostkiFirmy item1 = Model.GetJednostkaFirma(int.Parse(KPPage.Current.JednostkaID));
            excelCell.Value = item1.JednostkaNazwa;
            vKP_Swieta[] ListaSwiat;

            for (int iMonth = month1; iMonth < month2; iMonth++)
            {
                ListaSwiat = Kalendarz.GetSwieta(year, iMonth);

                int lastDayMonth = FunctionGlobal.IleDniMiesiac(year, iMonth);
                DateTime dDateDyzur = new DateTime(year, iMonth, 1);
                int IDTemp = DyzuryK.PobierzGlowneDyzurDokumentID(int.Parse(Current.JednostkaID), dDateDyzur);
                if (IDTemp == 0) continue;
              
                
                
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("C4", "C4").Offset[iTemp, 0];
                excelCell.Value = MonthNames[iMonth - 1] + " / " + year.ToString();
                excelCell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Navy);

                DateTime d = new DateTime();
                for (int i = 0; i < lastDayMonth; i++)
                {
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("G5", "G5").Offset[iTemp, i];
                    excelCell.Value = (i + 1).ToString();

                }
                for (int i = 0; i < lastDayMonth; i++)
                {
                    d = new DateTime(year, iMonth, i + 1);
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("G6", "G6").Offset[iTemp, i];
                    excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;

                    if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                                      excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
                 
                }

                foreach (vKP_Swieta sw in ListaSwiat)
                {
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("G6", "G6").Offset[iTemp, sw.day - 1];
                    excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlDouble;
                    excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalDown].LineStyle = MSExcel.XlLineStyle.xlDouble;
                    excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlDouble;
                }

                Model model = new Model();

                excelCellSource = (MSExcel.Range)excelWorksheet.get_Range("G6", "AK6").Offset[iTemp, 0];
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("C6", "C6");
                int iInic = 0;
               // int iosobaID = 0;

                var qOsoby = from item in DyzuryK.GetListaOsobDyzury(int.Parse(Current.JednostkaID),IDTemp)
                             select new { item.NazwiskoImie, item.OsobaID, item.Tytul, item.DokumentID };
             
                foreach (var os in qOsoby.Distinct().OrderBy(a=>a.NazwiskoImie))
                {
                    if (iInic > 0)
                    {
                        excelCellTarget = (MSExcel.Range)excelWorksheet.get_Range("G6", "AK6").Offset[iTemp, 0];
                        excelCellSource.Copy(excelCellTarget);
                        excelCellTarget.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                    }
                 // iosobaID = os.OsobaID;
                    var qOsobaDyzury = from item2 in DyzuryK.GetDyzuryDlaOsoby(os.OsobaID, os.DokumentID) select new { item2.Date };
                //  IEnumerable<DateTime> qOsobaDyzury = from item2 in DyzuryK.GetDyzuryOsoby(iosobaID, IDTemp) select new { item2.Date };
                    foreach (var iUr in qOsobaDyzury)
                    {
                        excelCell.Offset[iTemp, iUr.Date.Day + 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DodgerBlue);
                    }
                    excelCell.Offset[iTemp, 0].Value =
                              (typ == 1 ? os.Tytul.ToLower() : "") + "\r\n" + FunctionGlobal.UppercaseFirstWords(os.NazwiskoImie);
                    excelCell.Offset[iTemp, 3].Value = (iInic + 1).ToString();
                   iInic += 1;
                   iTemp += 1;

                }

                iTemp += 4;
            }

            excelApp.Visible = true;
            return 0;
        }

        protected void DyzuryView_Click(object sender, EventArgs e)
        {
            int iTemp = DyzuryWyswietlExcel1(1, 2013, 7,12);
        }
        protected void btnRoboczyClick(object sender, EventArgs e)
        {
            DateTime dd1 = DateTime.Parse(((Label)((Button)sender).Parent.FindControl("oddata")).Text);
            int iTemp = DyzuryWyswietlExcel1(1, dd1.Year, dd1.Month, dd1.Month+1);
        }
    }
}